package uia.alumni.web;

import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import uia.alumni.data.User;
import uia.alumni.form.*;

import static uia.alumni.form.FieldType.*;
import static uia.alumni.web.Constants.*;

/**
 * Login user and return to HOME.
 *
 * @author Even Åby Larsen (even.larsen@uia.no)
 * @author (edited by) Simon Zimmermann(simonz05@gmail.com)
 * @date Nov 3rd 2009.
 */
public class Login extends Command {

    public static final String SERVLET_NAME = "login";
    public final static long serialVersionUID = 1;
    @PersistenceUnit(name = PERSISTENCE_UNIT)
    private EntityManagerFactory emf;

    public Login() {
        super(null);
    }
    
    @Override
    public void execute(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        EntityManager em = emf.createEntityManager();
        boolean success = false;
        try {
            Form form = new Form(request);
            String email = form.newField(USERNAME, TEXT).getFieldValue();
            String password = form.newField(PASSWORD, TEXT).getFieldValue();

            if (form.isValid()) { 
                Query q = em.createNamedQuery("User.findByEmail");
                q.setParameter("email", email);
                User user = (User) q.getSingleResult();

                // Login User if He entered the correct info
                if (user != null && user.isUser(email, password)) {
                    request.getSession(true).setAttribute(USER, user);
                    log(user + " logged in");
                    success = true;
                }
            } else {
                addMessage(request, "Wrong username, password or both!");
                log("Login failed for '" + email + "/" + password + "'");
            }
        } catch (Exception e) {
            addMessage(request, e.getMessage());
        } finally {
            em.close();
            if(success)
                forwardTo(Home.SERVLET_NAME, request, response);
            //forwardTo("index.html", request, response);
            response.sendRedirect(START);
        }
    }
}
